/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.constant.KwConstant;
import me.zhengjie.domain.KwExamTeacher;
import me.zhengjie.kwService.ExamTeacherService;
import me.zhengjie.pojo.dto.ExamRoomFindPageDto;
import me.zhengjie.pojo.dto.ExamTeacherAddReplaceDto;
import me.zhengjie.pojo.dto.SaveExamTeacherDto;
import me.zhengjie.pojo.entity.ExamTeacher;
import me.zhengjie.pojo.export.ExamTeacherExport;
import me.zhengjie.service.KwExamTeacherService;
import me.zhengjie.service.dto.KwExamTeacherQueryCriteria;
import me.zhengjie.util.BaseResponse;
import me.zhengjie.util.KwUtils;
import me.zhengjie.util.ruoyiexcel.ExcelUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @date 2021-06-28
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "考场监考老师安排表前端控制器管理")
@RequestMapping("/api/kwExamTeacher")
@Slf4j
public class KwExamTeacherController {

    private final KwExamTeacherService kwExamTeacherService;
    private final ExamTeacherService examTeacherService;
    private final KwUtils kwUtils;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('kwExamTeacher:list')")
    public void download(HttpServletResponse response, KwExamTeacherQueryCriteria criteria) throws IOException {
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) return;
        kwExamTeacherService.download(kwExamTeacherService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询考场监考老师安排表前端控制器")
    @ApiOperation("查询考场监考老师安排表前端控制器")
    @PreAuthorize("@el.check('kwExamTeacher:list')")
    public ResponseEntity<Object> query(KwExamTeacherQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(kwExamTeacherService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增考场监考老师安排表前端控制器")
    @ApiOperation("新增考场监考老师安排表前端控制器")
    @PreAuthorize("@el.check('kwExamTeacher:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody KwExamTeacher resources) throws Exception {
        kwUtils.hasPermission(Arrays.asList(resources.getExamId()), Arrays.asList(resources.getDeptId()));
        return new ResponseEntity<>(kwExamTeacherService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改考场监考老师安排表前端控制器")
    @ApiOperation("修改考场监考老师安排表前端控制器")
    @PreAuthorize("@el.check('kwExamTeacher:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody KwExamTeacher resources) throws Exception {
        Integer examId = resources.getExamId();
        Integer deptId = resources.getDeptId();
        kwUtils.hasPermission(Arrays.asList(examId), Arrays.asList(deptId));
        kwExamTeacherService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除考场监考老师安排表前端控制器")
    @ApiOperation("删除考场监考老师安排表前端控制器")
    @PreAuthorize("@el.check('kwExamTeacher:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) throws Exception {
        List<ExamTeacher> examTeachers = examTeacherService.getBaseMapper().selectBatchIds(Arrays.asList(ids));
        List<Integer> examIds = examTeachers.stream().map(ExamTeacher::getExamId).collect(Collectors.toList());
        List<Integer> deptIds = examTeachers.stream().map(ExamTeacher::getDeptId).collect(Collectors.toList());
        kwUtils.hasPermission(examIds, deptIds);
//        String identity = kwUtils.identity();
//        if (!Objects.equals(KwConstant.ADMIN, identity)) {
//            if (!Objects.equal高数考场二s(KwConstant.EXAM, identity) && !Objects.equals(KwConstant.EXAM_DEPT, identity)) {
//                throw new ParameterException("无权操作");
//            }
//            List<ExamTeacher> examTeachers = examTeacherService.getBaseMapper().selectBatchIds(Arrays.asList(ids));
//            kwUtils.isPermission(examTeachers.stream().map(ExamTeacher::getExamId).collect(Collectors.toList()));
//        }
        kwExamTeacherService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }



    /*-------------------------------------------------------------------------------*/

    @ApiOperation("考场监考老师安排信息导出")
    @PostMapping("/ruoyiExport")
    @PreAuthorize("@el.check('kwExamTeacher:ruoyiExport')")
    public BaseResponse export(HttpServletResponse response, @RequestBody List<ExamTeacher> examTeachers) throws Exception {
        try {
            return examTeacherService.export(response, examTeachers);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导出失败：" + e.getMessage());
        }
    }

    @ApiOperation("考场监考老师信息导入")
    @PostMapping("/ruoyiImport")
    @PreAuthorize("@el.check('kwExamTeacher:ruoyiImport')")
    public BaseResponse ruoYiImport(@RequestParam(value = "file") MultipartFile file, @RequestParam("examId") Integer examId) throws Exception {
        if (file.isEmpty()) {
            return BaseResponse.failed("导入了空文件");
        }
        String fileName = file.getResource().getFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println("后缀名:" + suffix);
        if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
            return BaseResponse.failed("请导入xls，xlsx文件");
        }
        ExcelUtil<ExamTeacherExport> util = new ExcelUtil<>(ExamTeacherExport.class);
        try {
            List<ExamTeacherExport> examTeacherExports = util.importExcel(file.getInputStream());
            if (examTeacherExports.isEmpty()) {
                return BaseResponse.failed("导入文件为空");
            }
            examTeacherService.saveImportList(examTeacherExports, examId);
            return BaseResponse.ok("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导入失败：" + e.getMessage());
        }
    }

    @ApiOperation("考场监考老师信息模板下载")
    @GetMapping("/import-ExamTeacher")
    @PreAuthorize("@el.check('kwExamTeacher:template')")
    public void importKwExam(HttpServletResponse response) throws Exception {
        ExcelUtil<ExamTeacherExport> excelUtil = new ExcelUtil<>(ExamTeacherExport.class);
        /*excelUtil.importTemplateExcel("考场监考老师信息");*/
        excelUtil.importTemplateExcel(response, "考场监考老师信息");
    }

    @ApiOperation("新增监考教师安排信息及教师占用信息")
    @PostMapping("/save")
    @PreAuthorize("@el.check('kwExamTeacher:save')")
    public BaseResponse saveExamTeacher(@RequestBody @Validated SaveExamTeacherDto dto) throws Exception {
        kwUtils.hasPermission(Arrays.asList(dto.getExamId()), Arrays.asList(dto.getDeptId()));
        return examTeacherService.saveExamTeacher(dto);
    }

    @ApiOperation("给监考老师安排替补老师")
    @PostMapping("/addReplaceTeacher")
    @PreAuthorize("@el.check('kwExamTeacher:addReplaceTeacher')")
    public BaseResponse addReplaceTeacher(@RequestBody @Validated ExamTeacherAddReplaceDto dto) throws Exception {
        ExamTeacher examTeacher = examTeacherService.getBaseMapper().selectById(dto.getId());
        kwUtils.hasPermission(Arrays.asList(examTeacher.getExamId()), Arrays.asList(examTeacher.getDeptId()));
        return examTeacherService.addReplaceTeacher(dto);
    }


    @ApiOperation("根据用户角色返回所被分配的考试任务考场")
    @PostMapping("/findPlanRoom")
    public ResponseEntity findPlanRoom(@RequestBody @Validated ExamRoomFindPageDto dto) {
        return new ResponseEntity<>(examTeacherService.findPlanRoom(dto), HttpStatus.OK);
    }
}